import urllib
import base64
import logging
from google.appengine.api import urlfetch
import dal
import CQstrings
import time

def enum(**enums):
    return type('Enum', (), enums)

EPositionStatus = enum(INLINE=0, IN_PROCESS=1, POST_PROCESS=2, LEFT=3)
EQueueStatus = enum(RUNNING=0, TERMINATED=1, DELETED=2)

def notify_next_users(users, ext=None):
    if len(users) >= 1:
        if ext is not None and ext != "0":
            # a = ext.encode('ascii','ignore')
            _notifiy_user(users[0], CQstrings.current_user_with_ext + str(ext))
        else:
            _notifiy_user(users[0], CQstrings.current_user)
    time.sleep(1)
    if len(users) >= 2:
        _notifiy_user(users[1], CQstrings.next_user)
  
def _notifiy_user(user_id, text):
    details = dal.get_user_details(user_id)
    if details.has_key("phone"):
        try:
            _send_sms(details["phone"], text)
        except:  
            pass
        
def _send_sms(phone, contet):
    if phone is None or phone.lower() == "x" or len(phone) < 7:
        return
    phone = phone.replace("-", "")
    phone = "+972" + phone
    twilio_sms_url = "https://api.twilio.com/2010-04-01/Accounts/AC0bf755975e6842838d07182229e33429/SMS/Messages"
    form_fields = {
                   "From" : "+13175654389",
                   "To" : phone,
                   "Body" : contet }
    form_data = urllib.urlencode(form_fields)
    response = urlfetch.fetch(url=twilio_sms_url,
                        payload=form_data,
                        method=urlfetch.POST,
                        headers={"Authorization": 
                                       "Basic %s" % base64.b64encode("AC0bf755975e6842838d07182229e33429:c3cdb67a58e2f9522a0726032b029be2")})
    logging.info(str(response.content))   
